package com.wn.class30.cotroller.weixin;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.wn.class30.entity.Business;
import com.wn.class30.entity.Integral;
import com.wn.class30.entity.PayOrder;
import com.wn.class30.service.*;
import com.wn.class30.tools.MoneyUtils;
import com.wn.class30.tools.UserIp;
import com.wn.class30.tools.UseridUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.weixin4j.spring.WeixinTemplate;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping(value = "/weixin")
public class AliTest {
    @Resource
    private BusinessService businessService;
    @Resource
    private UserService userService;
    @Resource
    private WeixinTemplate weixinTemplate;
    @Resource
    private UseridUtils useridUtils;
    @Resource
    private WXPayOrderService wxPayOrderService;

    @Resource
    private IntegralService integralService;

    @Resource
    private VipService vipService;
    private final String APP_ID = "2016102100729241";
    private final String APP_PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCKIsHweNZJrpIeyb1ObxIfhpvlZyy+acPabcn1BAHknzMFm/nbNYRFBWWibk1cBfqmlDrDEA8dk8k65yLvIn5gVJWfFZl1jJwvPrZKhgOV6VNwOjuqsuuq/3vRFmCRpTEHUrRYR196F0Hk6PprU6R+CAF2q2yDT5yHkLnooE4ny91jVwENgrYIGaQWF7zL9Fu1P6Ycoc09OCbw3gMp8GZvHwIzStuiGu9nJUx6e66+wfQyPQUrnn2V3ySeJG5PVujfh63Tgs8/S3fGB5/nVB61AdibLndYSpOgtjOen288TnufAJyuiegpgxB0iFv/qEhveLcwpkgIazgbXpzKf13vAg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MctPegzMYzQMQtpUQ5xTgDzyWF20MeUN384cYTYVl/AvBB4Xwi/2RQL7fXv7T4NryVn8XljQaqcRuR6X9pCV2MNVIex8hzsng3I5ZJ4oWBXalSFhV48wS9uXVoDkM0ao1riB0FRYxeWALCUHH83NYXjaLbMzRabiQQ==";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm8XxzxTIXRLZQV05kDH1ZAgv68EhGM65x/+qAPfTp8R2lZDFiftf+vGWPWZnzcUJRQeB8bMbXUwN5YMvKJ/lVULzcsfUPakHVPuze82b4AaE8NjS7fga4f4OFdqEwoOu1U/kt5m7S8rGUhLgvmUOh18KqIFFCTh4/w1x7BoUURfjPNbZ9PV1lIwpoq+PEvbCYH1++/tPvqBfgABcOSiZTlJoGDgNAy1huEuYLQS/J46+WLqb3cdsd+jG5KnO7yD1DMslwYpq9JVsX6GBFwQlK+VU1GMt7NIC9Fot8IWApbg5SIZadpc8oVMnjP0K6Da2WUy6ooUgaGm+wXOhBIBXJwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://zhouhao1.ngrok2.xiaomiqiu.cn/weixin/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://zhouhao1.ngrok2.xiaomiqiu.cn/weixin/returnUrl";

    @RequestMapping("/alipay")
    public void alipay(HttpServletResponse httpResponse) throws IOException {

        Random r=new Random();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount =Integer.toString(8888);
        //订单名称，必填
        String subject ="奥迪A8 2016款 A8L 60 TFSl quattro豪华型";
        //商品描述，可空
        String body = "尊敬的会员欢迎购买奥迪A8 2016款 A8L 60 TFSl quattro豪华型";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
    @RequestMapping(value = "alitelpay")
    public void alitelpay(HttpServletRequest httpRequest, HttpServletResponse response,Double payMoney) throws Exception {
        AlipayClient client = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
        // 封装请求支付信息
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        String orderIdByTime = UserIp.getOrderIdByTime();
        model.setOutTradeNo(orderIdByTime);
        model.setSubject("禄舍轩商城");
        model.setTotalAmount(payMoney+"");
        model.setBody("尊敬的用户欢迎到禄舍轩连锁店消费");
        model.setTimeoutExpress("2m");
        model.setProductCode("QUICK_WAP_WAY");
        alipay_request.setBizModel(model);
        // 设置异步通知地址
        alipay_request.setReturnUrl(RETURN_URL);
        alipay_request.setNotifyUrl(NOTIFY_URL);
        // 设置同步地址
        PayOrder payOrder = new PayOrder();
        payOrder.setBussinessId((Integer) httpRequest.getSession().getAttribute("wxpaybusinessid"));
        Business wxpaybusinessid = businessService.selectBusinessById((Integer) httpRequest.getSession().getAttribute("wxpaybusinessid"));
        payOrder.setPayMoney(payMoney);
        payOrder.setPayOrderState("0");
        payOrder.setPayUpdateTime(new Date());
        payOrder.setPayOrderNumber(orderIdByTime);
        payOrder.setUserId(useridUtils.queryUseridByOptenid(httpRequest));
        payOrder.setBusinessName(wxpaybusinessid.getBusinessName());
        wxPayOrderService.insertPayOrder(payOrder);
        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = client.pageExecute(alipay_request).getBody();
            System.out.println(form);
            response.setContentType("text/html;charset=" + CHARSET);
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



    @RequestMapping(value = "returnUrl")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            //支付成功，修复支付状态
    /*        payService.updateById(Integer.valueOf(out_trade_no));*/
            return "/weixin/queryIndex";//跳转付款成功页面
        }else{
            return "fail";//跳转付款失败页面
        }

    }

    @RequestMapping(value = "notifyUrl")
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        System.out.println("=================================异步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);
            PayOrder payOrder = wxPayOrderService.queryPayOrderByOrderNum(out_trade_no);
            if (payOrder != null && payOrder.getPayOrderState().equals("0")) {
                payOrder.setPayOrderState("1");
                wxPayOrderService.updatePayOrder(payOrder);
                Integral integral = integralService.queryIntegral();
                Double ratio = integral.getRatio();
                double mul = MoneyUtils.mul(ratio, payOrder.getPayMoney());
                double floor = Math.floor(mul);
                userService.updatePointsByUserid(payOrder.getUserId(), (int) floor);
                vipService.updateVipLv(payOrder.getUserId());
            }

            //支付成功，修复支付状态
            /*        payService.updateById(Integer.valueOf(out_trade_no));*/
            response.getWriter().write("success");
        }else{
            response.getWriter().write("fail");
        }
    }
}


